package com.lgj.rocketmq.message;


import com.alibaba.fastjson.JSONObject;
import com.lgj.exception.BusinessException;
import io.netty.util.internal.StringUtil;
import org.apache.rocketmq.common.message.Message;

/**
 * @author: guangjie.liao
 * @Date: 2023/9/19 22:12
 * @Description: 消息构建
 */
public class RocketMessageBuilder<T> {
    public static RocketMessageBuilder builder(){
        return new RocketMessageBuilder();
    }
    private String topic;
    private T body;
    private String tags;
    private int delayTimeLevel;

    public RocketMessageBuilder topic(String topic){
        this.topic = topic;
        return this;
    }

    public RocketMessageBuilder body(T body){
        this.body = body;
        return this;
    }

    public RocketMessageBuilder tags(String tags){
        this.tags = tags;
        return this;
    }

    public RocketMessageBuilder delayTimeLevel(int delayTimeLevel){
        this.delayTimeLevel = delayTimeLevel;
        return this;
    }

    public Message build(){
        Message message = new Message();
        if (this.topic == null){
            throw new BusinessException("mq 消息设置错");
        }
        if (this.body == null){
            throw new BusinessException("mq 消息内容设置错");
        }
        message.setTopic(topic);
        message.setBody(JSONObject.toJSONBytes(new RocketMessage<>(topic,this.body)));
        if (!StringUtil.isNullOrEmpty(this.tags)){
            message.setTags(tags);
        }
        if (delayTimeLevel != 0){
            message.setDelayTimeLevel(delayTimeLevel);
        }
        return message;
    }
}
